package digital.store.springmvc.controller;


import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import digital.store.springmvc.service.CustomerService;
import digital.store.springmvc.service.OrderService;
import digital.store.tutorial.springmvc.model.Customer;
import digital.store.tutorial.springmvc.model.Orderk;
import digital.store.tutorial.springmvc.model.Product;
import digital.store.tutorial.springmvc.model.ShoppingCart;



@Controller
@RequestMapping(value="/mycart")
public class MyCartController {
	
	@Autowired
	private OrderService orderService;
	@Autowired
	private CustomerService customerService;
	
	@RequestMapping(method = RequestMethod.GET)
	 public String list(Model model,HttpSession session) {
		if (session.getAttribute("mycart")!=null)
		{
			ShoppingCart mycart = (ShoppingCart)session.getAttribute("mycart");
			Collection<Product> products = mycart.getProducts().values();
			model.addAttribute("products", products);
			model.addAttribute("total",mycart.getTotal());
		}
		model.addAttribute(new Customer());
		return "/mycart";
   }
	
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public String save(Customer customer,BindingResult result,HttpSession session)
		{
			if (result.hasErrors()){
				return "redirect:/home/";	
			}
			ShoppingCart cart = (ShoppingCart) session.getAttribute("mycart");
			Orderk order = new Orderk();
			order.setProducts(cart.getProducts());
			order.setTotal(cart.getTotal());
			orderService.saveOrUpdate(order);		
			customerService.saveOrUpdate(customer);
			return "redirect:/home/";	
		}
}
